using System;
using ETModel;
using System.Linq;
using UnityEngine;

namespace ETHotfix
{
    public static class MapHelper
    {
        public static async ETVoid EnterMapAsync()
        {
            try
            {
                // 加载Unit资源
                ResourcesComponent resourcesComponent = ETModel.Game.Scene.GetComponent<ResourcesComponent>();
                await resourcesComponent.LoadBundleAsync($"unit.unity3d");

                // 加载场景资源
                await ETModel.Game.Scene.GetComponent<ResourcesComponent>().LoadBundleAsync("map.unity3d");
                // 切换到map场景
                using (SceneChangeComponent sceneChangeComponent = ETModel.Game.Scene.AddComponent<SceneChangeComponent>())
                {
                    await sceneChangeComponent.ChangeSceneAsync(SceneType.Map);
                }
                //加载场景地形对象
                GameUnitFactory.LoadGameObjectByBundle("Unit.unity3d", "Unit", "Terrain1");

                G2C_EnterMap g2CEnterMap = await SessionComponent.Instance.Session.Call(new C2G_EnterMap { }) as G2C_EnterMap;
                if (g2CEnterMap.Error > 0) {
                    Log.Error("进入地图失败:" + g2CEnterMap.Message);
                    return;
                }
                GameUnitFactory.LoadUnitsByInfos(g2CEnterMap.Units);

                var myUnits = g2CEnterMap.SelfUnitIds.ToList();
                var myUnitId = myUnits.FirstOrDefault();//暂时只取第一个作为控制单位
                var myUnit = Game.Scene.GetComponent<UnitsComponent>().Get(myUnitId);
                PlayersComponent.Instance.MyPlayer.UnitIds = myUnits;
                PlayersComponent.Instance.MyUnit = myUnit;


                var cameraComp = Game.Scene.AddComponent<FollowUnitCameraComponent>();
                cameraComp.FollowUnit = myUnit;
                cameraComp.CameraHeight = 10;
                Game.Scene.AddComponent<OperaComponent>().OperaUnit = myUnit;


                Game.EventSystem.Run(HotfixEventIdType.EnterMapFinish);
            }
            catch (Exception e)
            {
                Log.Error(e);
            }	
        }
    }
}